package com.rentong.wx.cust.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rentong.common.R;
import com.rentong.wx.cust.dao.*;
import com.rentong.wx.cust.domain.*;
import com.rentong.wx.cust.dto.*;
import com.rentong.wx.cust.service.CustUserServiceService;
import com.rentong.wx.sys.dao.SysCityDao;
import com.rentong.wx.sys.dao.SysServiceDao;
import com.rentong.wx.sys.domain.SysServiceEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class CustUserServiceServiceImpl implements CustUserServiceService {

    @Resource
    private CustUserServiceDao custUserServiceDao;

    @Autowired
    private CustUserCaixiDao custUserCaixiDao;

    @Autowired
    private WxCustUserMapper wxCustUserMapper;

    @Autowired
    private SysCityDao sysCityDao;

    @Autowired
    private CustServiceOrderDao custServiceOrderDao;

    @Autowired
    private CustUserChefPicDao custUserChefPicDao;

    @Autowired
    private SysServiceDao sysServiceDao;

    @Autowired
    private CustGuanzhuDao custGuanzhuDao;

    @Autowired
    private CustUserServiceTimeDao custUserServiceTimeDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R updateCustUserInfo(Long custId, CustUserInfoDto custUserInfoDto) {
        if (ObjectUtil.isNotEmpty(custUserInfoDto)) {

            //如果设置过了服务时间，并且第一次设置服务介绍，则设置用户为师傅
            CustUserServiceTimeEntity custUserServiceTimeEntity = custUserServiceTimeDao.getbyCustId(custId);
            if (ObjectUtil.isNotEmpty(custUserServiceTimeEntity)) {
                List<CustUserServiceEntityDto> serviceByCustId = custUserServiceDao.getServiceByCustId(custId);
                if (CollectionUtil.isEmpty(serviceByCustId)) {
                    WxCustUser wxCustUser = new WxCustUser();
                    wxCustUser.setCustId(custId);
                    wxCustUser.setGrade(2);
                    wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
                }
            }
            //更新服务表
            if (custUserInfoDto.getServiceIds() != null) {
                //服务表有更新
                List<Integer> serviceIds = custUserInfoDto.getServiceIds();
                custUserServiceDao.deleteByCustId(custId);

                for (Integer serviceId : serviceIds) {
                    CustUserServiceEntity custUserServiceEntity = new CustUserServiceEntity();
                    custUserServiceEntity.setCustId(custId);
                    custUserServiceEntity.setServiceId(Long.valueOf(serviceId));

                    SysServiceEntity sse = sysServiceDao.selectByPrimaryKey(custUserServiceEntity.getServiceId());

                    Integer serviceType = 1;
                    BigDecimal serviceAmount = sse.getMorningAmount();

                    if (sse.getBigTypeId() == 1) {
                        if (sse.getAfternoonAmount().compareTo(serviceAmount) < 0) {
                            serviceType = 2;
                            serviceAmount = sse.getAfternoonAmount();
                        }
                        if (sse.getNightAmount().compareTo(serviceAmount) < 0) {
                            serviceType = 3;
                            serviceAmount = sse.getNightAmount();
                        }
                        if (sse.getAllDayAmount().compareTo(serviceAmount) < 0) {
                            serviceType = 4;
                            serviceAmount = sse.getAllDayAmount();
                        }

                    } else {
                        serviceAmount = sse.getMinAmount();
                    }

                    custUserServiceEntity.setServiceType(serviceType);
                    custUserServiceEntity.setServiceAmount(serviceAmount);

                    custUserServiceEntity.setAddTime(new Date());
                    custUserServiceDao.insert(custUserServiceEntity);
                }
            }


            //更新擅长菜系表
            if (ObjectUtil.isNotEmpty(custUserInfoDto.getCaixiIds())) {
                List<Integer> caixiIds = custUserInfoDto.getCaixiIds();
                custUserCaixiDao.deleteByCustIdAndCaixiId(custId);

                for (Integer caixiId : caixiIds) {
                    CustUserCaixiEntity custUserCaixiEntity = new CustUserCaixiEntity();
                    custUserCaixiEntity.setCustId(custId);
                    custUserCaixiEntity.setCaixiId(Long.valueOf(caixiId));
                    custUserCaixiEntity.setAddTime(new Date());
                    custUserCaixiDao.insert(custUserCaixiEntity);
                }
            }


            //更新菜品图片
            if (ObjectUtil.isNotEmpty(custUserInfoDto.getChefPics())) {
                List<String> chefPics = custUserInfoDto.getChefPics();
                custUserChefPicDao.deleteByCustId(custId);
                for (String chefPic : chefPics) {
                    CustUserChefPicEntity custUserChefPicEntity = new CustUserChefPicEntity();
                    custUserChefPicEntity.setCustId(custId);
                    custUserChefPicEntity.setChefPicUrl(chefPic);
                    custUserChefPicEntity.setAddTime(new Date());
                    custUserChefPicDao.insert(custUserChefPicEntity);
                }
            }


            //厨师修改城市的时候，需要判断下，当前已经成交的单子已经全部完成了
            WxCustUser wxCustUser = wxCustUserMapper.getUserInfoByCustId(custId);
            if (StrUtil.isNotEmpty(custUserInfoDto.getCityName())) {
                String provinceName = custUserInfoDto.getProvinceName();
                String cityName = custUserInfoDto.getCityName();
                String regionName = custUserInfoDto.getRegionName();

                CityHierarchy cityHierarchy = sysCityDao.getByRegionName(regionName);
                //如果是第一次插入地址
                if (StrUtil.isEmpty(wxCustUser.getCityName())) {
                    wxCustUser.setProvinceName(provinceName);
                    wxCustUser.setCityName(cityName);
                    wxCustUser.setProvinceId(cityHierarchy.getProvinceId());
                    wxCustUser.setCityId(cityHierarchy.getCityId());
                }
                //如果城市名字不相同，判断单子是否全部完成
                if (!StrUtil.equals(cityName, wxCustUser.getCityName())) {
                    int result = custServiceOrderDao.getByOrderStat(custId);
                    if (result > 0) {
                        return R.error("单子未全部完成，修改城市失败");
                    }
                    wxCustUser.setProvinceName(provinceName);
                    wxCustUser.setCityName(cityName);
                    System.out.println(cityHierarchy);
                    wxCustUser.setProvinceId(cityHierarchy.getProvinceId());
                    wxCustUser.setCityId(cityHierarchy.getCityId());
                }
                wxCustUser.setRegionName(regionName);
                wxCustUser.setRegionId(cityHierarchy.getRegionId());

            }
            if (custUserInfoDto.getShopTypeIds() != null && !custUserInfoDto.getShopTypeIds().isEmpty()) {
                List<Long> shopTypeIds = custUserInfoDto.getShopTypeIds();

                String shopTypeIdsStr = "";
                for (int i = 0; i < shopTypeIds.size(); i++) {
                    shopTypeIdsStr = shopTypeIdsStr + shopTypeIds.get(i).toString() + ",";
                }

                wxCustUser.setShopTypeIds(shopTypeIdsStr.length() > 0 ? shopTypeIdsStr.substring(0, shopTypeIdsStr.length() - 1) : shopTypeIdsStr);
            }


            if (custUserInfoDto.getOrderRange() != null && !custUserInfoDto.getOrderRange().isEmpty()) {
                wxCustUser.setOrderRange(custUserInfoDto.getOrderRange());
            }

            wxCustUser.setCustId(custId);
            wxCustUser.setUpdateTime(new Date());
            wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
            return R.success();
        }

        return R.error("参数不能为空");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCustUserStatus(Long currentCustId) {
        WxCustUser wxCustUser = wxCustUserMapper.getUserInfoByCustId(currentCustId);
        if (wxCustUser == null) {
            throw new RuntimeException("用户不存在");
        }
        //接单状态切换1：接单中，2：休息
        if (wxCustUser.getJiedanState().equals(1)) {
            wxCustUser.setJiedanState(2);
        } else if (wxCustUser.getJiedanState().equals(2)) {
            wxCustUser.setJiedanState(1);
        }
        //更新接单状态
        wxCustUserMapper.updateByPrimaryKeySelective(wxCustUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxCustUserGeRenDaTingDto getCustUserInfo(Long currentCustId) {
        /*需要的字段：1.用户名 2.头像 3.关注数 4.粉丝数 5.接单状态 6.今日收益 7.接单总数 8.好评率 9.合作店铺数量
        10.账户余额 11.待预约数量state:1 12.待接单数量state:2 13.待服务数量state:3 14.服务中state:4
        15.待确认数量state:5 16.售后中数量state:8 17.是否是会员*/
        WxCustUser wxCustUser = wxCustUserMapper.getUserByCustId(currentCustId);
        if (wxCustUser == null) {
            throw new RuntimeException("用户不存在");
        }
        WxCustUserGeRenDaTingDto wxCustUserGeRenDaTingDto = new WxCustUserGeRenDaTingDto();
        BeanUtil.copyProperties(wxCustUser, wxCustUserGeRenDaTingDto);
        //把wxCustUser中不存在的字段手动输入到DTO中
        //关注和粉丝的数量
        wxCustUserGeRenDaTingDto.setFensi(custGuanzhuDao.getFensiNum(wxCustUser.getCustId()));
        wxCustUserGeRenDaTingDto.setGuanzhu(custGuanzhuDao.getGuanzhuNum(wxCustUser.getCustId()));
        //计算好评率
        Long pingjiaNum = wxCustUser.getPingjiaNum();
        Long haopingNum = wxCustUser.getHaopingNum();
        Long haopingRate = 0L;
        if (pingjiaNum != 0L) {
            haopingRate = haopingNum * 100 / pingjiaNum;
        }
        wxCustUserGeRenDaTingDto.setHaopingRate(haopingRate);
        //判断该用户是否是会员
        Date huiyuanTime = wxCustUser.getHuiyuanTime();
        Date now = new Date();
        boolean ishuiyuan = huiyuanTime != null && huiyuanTime.after(now);
        wxCustUserGeRenDaTingDto.setIshuiyuan(ishuiyuan);
        //查询并设置师傅端应该显示的订单状态
        List<orderStateNum> orderState = custServiceOrderDao.getOrderStateList(currentCustId);
        for (orderStateNum orderStateNum : orderState) {
            if (orderStateNum.getOrderState() == 1) {
                wxCustUserGeRenDaTingDto.setWaitAppointmentCount(orderStateNum.getNum());
            } else if (orderStateNum.getOrderState() == 2) {
                wxCustUserGeRenDaTingDto.setWaitOrderCount(orderStateNum.getNum());
            } else if (orderStateNum.getOrderState() == 3) {
                wxCustUserGeRenDaTingDto.setWaitServiceCount(orderStateNum.getNum());
            } else if (orderStateNum.getOrderState() == 4) {
                wxCustUserGeRenDaTingDto.setServiceCount(orderStateNum.getNum());
            } else if (orderStateNum.getOrderState() == 5) {
                wxCustUserGeRenDaTingDto.setWaitConfirmationCount(orderStateNum.getNum());
            } else if (orderStateNum.getOrderState() == 8) {
                wxCustUserGeRenDaTingDto.setAfterSalesCount(orderStateNum.getNum());
            }
        }
        return wxCustUserGeRenDaTingDto;
    }


}